/*
 * Copyright 2000-2006 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intellij.gwt.i18n;

import com.intellij.lang.properties.psi.Property;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.Navigatable;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.PsiNameHelper;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * @author nik
 */
public class GwtI18nUtil {
  public static final Icon IMPLEMENTED_PROPERTY_METHOD_ICON = IconLoader.getIcon("/gutter/implementedMethod.png");
  @NonNls public static final String CONSTANTS_INTERFACE_NAME = "com.google.gwt.i18n.client.Constants"; 
  @NonNls public static final String MESSAGES_INTERFACE_NAME = "com.google.gwt.i18n.client.Messages";
  @NonNls private static final String PROPERTY_METHOD_PREFIX = "getProperty";

  public static void navigateToProperty(@NotNull Property property) {
    ((Navigatable)property).navigate(true);
  }

  public static String convertPropertyName2MethodName(String propertyName, final PsiNameHelper nameHelper, final LanguageLevel languageLevel) {
    if (nameHelper.isIdentifier(propertyName, languageLevel)) {
      return propertyName;
    }

    final String[] words = propertyName.split("\\.");
    StringBuilder builder = new StringBuilder();
    for (String word : words) {
      String id = convert2Id(word);
      if (id.length() > 0) {
        if (builder.length() > 0) {
          id = StringUtil.capitalize(id);
        }
        builder.append(id);
      }
    }

    String id = builder.toString();
    if (!nameHelper.isIdentifier(id, languageLevel)) {
      id = PROPERTY_METHOD_PREFIX + StringUtil.capitalize(id);
      if (!nameHelper.isIdentifier(id, languageLevel)) {
        id = PROPERTY_METHOD_PREFIX;
      }
    }
    return id;
  }

  private static String convert2Id(final String word) {
    final StringBuilder builder = new StringBuilder();
    for (int i = 0; i < word.length(); i++) {
      char c = word.charAt(i);
      if (builder.length() == 0 && Character.isJavaIdentifierStart(c)
          || builder.length() > 0 && Character.isJavaIdentifierPart(c)) {
        builder.append(c);
      }
    }
    return builder.toString();
  }
}
